package com.education.ai.controller;

import com.education.ai.service.ExerciseService;
import com.education.ai.util.TeacherContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 习题库控制器
 */
@RestController
@Slf4j
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8080", "http://localhost:8081"}, allowCredentials = "true")
@RequestMapping("/api/exerciselibrary")
public class ExerciseLibraryController {

    @Autowired
    private ExerciseService exerciseService;

    /**
     * 获取历史记录
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getExerciseHistory(
            @RequestParam(required = false) String teacherId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "15") int size) {
        try {
            // 如果未提供teacherId，则从当前登录用户上下文获取
            if (teacherId == null || teacherId.isEmpty()) {
                teacherId = TeacherContext.getCurrentTeacherId();
                log.info("从当前登录上下文获取到教师ID: {}", teacherId);
            }

            if (teacherId == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("code", 400);
                errorResponse.put("message", "未提供教师ID且无法从上下文获取");
                errorResponse.put("data", null);
                return ResponseEntity.badRequest().body(errorResponse);
            }

            List<Map<String, Object>> history = exerciseService.getExerciseHistory(teacherId, page, size);
            
            // 提取总记录数
            long total = 0;
            if (!history.isEmpty() && history.get(0).containsKey("total")) {
                total = (long) history.get(0).remove("total");
            }
            
            // 如果只有一个记录且只包含total字段，则清空结果列表
            if (history.size() == 1 && history.get(0).size() == 1 && history.get(0).containsKey("total")) {
                history.clear();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "success");
            response.put("data", history);
            response.put("total", total);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取历史记录失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "获取历史记录失败: " + e.getMessage());
            errorResponse.put("data", null);
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
} 